package com.qxzn.app.medicalhealth.activity;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.MotionEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.OnDismissListener;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.bumptech.glide.request.RequestOptions;
import com.qxzn.app.api.api.HttpRequest;
import com.qxzn.app.api.util.EventBusManager;
import com.qxzn.app.bean.AddMedicineRemindBean;
import com.qxzn.app.bean.BaseBean;
import com.qxzn.app.bean.BaseRepeatDateBean;
import com.qxzn.app.bean.ContactsBean;
import com.qxzn.app.bean.EventBusBean;
import com.qxzn.app.bean.MedicineRemindDetailBean;
import com.qxzn.app.bean.MedicineViewBean;
import com.qxzn.app.bean.TimesBean;
import com.qxzn.app.medicalhealth.R;
import com.qxzn.app.medicalhealth.R2;
import com.qxzn.app.medicalhealth.adapter.RemindTimeAdapter;
import com.qxzn.app.page.BaseActivity;
import com.qxzn.app.page.util.GlideImageLoader;
import com.qxzn.app.page.view.CustomItemView;
import com.qxzn.app.page.view.MyRecyclerView;
import com.qxzn.app.page.view.VoicePickerView;
import com.qxzn.app.util.AppUtil;
import com.qxzn.app.util.Constant;
import com.qxzn.app.util.DateUtil;
import com.qxzn.app.util.DisplayUtil;
import com.qxzn.app.util.FileUtil;
import com.qxzn.app.util.MathUtil;
import com.qxzn.app.util.SharePreferenceUtil;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.internal.entity.CaptureStrategy;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import news.jaywei.com.compresslib.CompressTools;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * 编辑提醒
 */

public class EditRemindActivity extends BaseActivity {
    @BindView(R2.id.tv_save)
    TextView tvSave;
    @BindView(R2.id.tv_name)
    TextView tvName;
    @BindView(R2.id.tv_age)
    TextView tvAge;
    @BindView(R2.id.iv_head)
    ImageView ivHead;
    @BindView(R2.id.iv_record)
    ImageView ivRecord;
    @BindView(R2.id.iv_delete_voice)
    ImageView ivDeleteVoice;
    @BindView(R2.id.voice_picker)
    VoicePickerView voicePicker;
    @BindView(R2.id.ll_medicine)
    LinearLayout llMedicine;
    @BindView(R2.id.rv_time)
    MyRecyclerView rvTime;
    @BindView(R2.id.civ_add_repeat)
    CustomItemView civAddRepeat;
    private List<TimesBean> timesList = new ArrayList<TimesBean>();
    private List<MedicineViewBean> medicineViewList = new ArrayList<MedicineViewBean>();
    private List<String> mSelected;
    private int type;
    private String value = "1";
    private BaseRepeatDateBean repeatDateBean;
    private String voicePath;
    private RemindTimeAdapter adapter;
    private RxPermissions rxPermissions;
    private ContactsBean.DataBean userBean;
    private String username;
    private String device_id;
    private MedicineRemindDetailBean.DataBean editBean;
    private String id;
    private String delIds = "";
    private boolean isDelOriginalVoice;

    @Override
    protected int initLayout() {
        return R.layout.activity_edit_remind1;
    }

    @Override
    protected void initView() {
//        llMedicine.getViewTreeObserver().addOnGlobalLayoutListener(() -> setStatusBar());
        ivRecord.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                v.getParent().requestDisallowInterceptTouchEvent(true);
                voicePicker.onPressToSpeakBtnTouch(v, event, new VoicePickerView.EaseVoiceRecorderCallback() {
                    @Override
                    public void onVoiceRecordComplete(String voiceFilePath, int voiceTimeLength) {
                        voicePath = voiceFilePath;
                        ivDeleteVoice.setVisibility(View.VISIBLE);
                        AppUtil.showLog("录音完成：" + voiceFilePath + "\n" + voiceTimeLength);
                    }
                });
                return true;
            }
        });
        rvTime.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));
        adapter = new RemindTimeAdapter(this, timesList, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getTime((int) v.getTag());
            }
        });
        rvTime.setAdapter(adapter);
    }

    @Override
    protected void iniTitleBar() {
    }

    @Override
    protected void initData(Bundle savedInstanceState) {
        userBean = (ContactsBean.DataBean) getIntent().getSerializableExtra("user_data");
        if (userBean != null) {//新增
            tv_title.setText("添加提醒");
            username = userBean.getMemName();
            device_id = SharePreferenceUtil.getDeviceId(this);
            String remark = userBean.getMemRemarks();
            if (!TextUtils.isEmpty(remark)) {
                remark = "(" + remark + ")";
            } else {
                remark = "";
            }
            tvName.setText(userBean.getMemName() + remark);
            tvAge.setText("年龄：" + userBean.getAge() + "岁");
            Glide.with(this).load(userBean.getHeadportrait()).apply(RequestOptions.bitmapTransform(new CircleCrop()).placeholder(R.mipmap.logo).error(R.mipmap.logo)).into(ivHead);

            addMedicineView(null);
            timesList.add(new TimesBean("- - : - -", 8888888888888l));
            adapter.notifyDataSetChanged();
        } else {//修改
            tv_title.setText("编辑提醒");
            editBean = (MedicineRemindDetailBean.DataBean) getIntent().getSerializableExtra("edit_data");
            if (editBean != null) {
                id = editBean.getId();
                username = editBean.getUsername();
                device_id = editBean.getDevice_id();
                String remark = editBean.getNiname();
                if (!TextUtils.isEmpty(remark)) {
                    remark = "(" + remark + ")";
                } else {
                    remark = "";
                }
                tvName.setText(editBean.getUsername() + remark);
                tvAge.setText("年龄：" + editBean.getAge() + "岁");
                Glide.with(this).load(HttpRequest.BASE_URL + editBean.getHeadportrait()).apply(RequestOptions.bitmapTransform(new CircleCrop()).placeholder(R.mipmap.logo).error(R.mipmap.logo)).into(ivHead);

                List<MedicineRemindDetailBean.DataBean.ResultdetailsBean> medicineList = editBean.getResultdetails();
                if (medicineList != null) {
                    for (MedicineRemindDetailBean.DataBean.ResultdetailsBean medicineBean : medicineList) {
                        addMedicineView(medicineBean);
                    }
                }

                String takeMedicineTime = editBean.getMedicinetime();
                if (!TextUtils.isEmpty(takeMedicineTime)) {
                    String[] timeList = takeMedicineTime.split(",");
                    if (timeList != null) {
                        for (String s : timeList) {
                            timesList.add(new TimesBean(s, DateUtil.parseStrToMillis(DateUtil.formMillisToStr(System.currentTimeMillis(), DateUtil.yearToDatePattern) + s, DateUtil.yearToDatePattern + DateUtil.hourToMinPattern)));
                        }
                        adapter.strSort(timesList);
                        adapter.notifyDataSetChanged();
                    }
                }

                type = editBean.getType();
                value = editBean.getTypevalue();
                if (type == 1) {
                    civAddRepeat.setLeftText("每" + DateUtil.getWeekStrByWeekNum(value, "周"));
                } else if (type == 2) {
                    civAddRepeat.setLeftText("每隔" + value + "天");
                } else {
                    civAddRepeat.setLeftText("每天");
                }

                voicePath = editBean.getRingtone();
                if (!TextUtils.isEmpty(voicePath)) {
                    ivDeleteVoice.setVisibility(View.VISIBLE);
                }

                TextView textView = new TextView(this);
                textView.setId(R.id.tv_delete);
                textView.setText("删除");
                textView.setTextColor(getResources().getColor(R.color.white));
                textView.setOnClickListener(this);
                ll_right_bar.addView(textView);
            } else {
                AppUtil.showToast(EditRemindActivity.this, "参数有误");
                finish();
                return;
            }
        }
    }

    @Override
    public void onClick(View view) {
        super.onClick(view);
        if (view.getId() == R.id.tv_delete) {
            showDialog("删除操作", "是否确认删除？删除之后数据将不可还原", (dialog, which) -> delMedicineRemind());
        }
    }

    @OnClick({R2.id.tv_save, R2.id.iv_add_picture, R2.id.iv_delete_voice, R2.id.civ_add_repeat, R2.id.iv_add_time})
    public void onViewClicked(View view) {
        int i = view.getId();
        if (i == R.id.tv_save) {
            commitData();
        } else if (i == R.id.iv_add_picture) {
            addMedicineView(null);
        } else if (i == R.id.iv_delete_voice) {
            if (editBean != null) {
                showDialog("删除操作", "是否确认删除原有的提醒声音？如需修改，请直接长按录制图标，重新录制提醒声音", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        isDelOriginalVoice = true;
                        FileUtil.deleteFile(new File(voicePath));
                        voicePath = null;
                        ivDeleteVoice.setVisibility(View.GONE);
                        AppUtil.showToast(EditRemindActivity.this, "录音文件已删除");
                    }
                });
            } else {
                FileUtil.deleteFile(new File(voicePath));
                voicePath = null;
                ivDeleteVoice.setVisibility(View.GONE);
                AppUtil.showToast(this, "录音文件已删除");
            }
        } else if (i == R.id.civ_add_repeat) {
            startActivityForResult(new Intent(this, AddRepeatDateActivity.class), 10000);
        } else if (i == R.id.iv_add_time) {
            timesList.add(new TimesBean("- - : - -", 8888888888888l));
            adapter.notifyDataSetChanged();
        }
    }

    private void commitData() {// TODO: 2019/7/19 上传后需要后台推送到桌面版
        showProgress();
        AddMedicineRemindBean bean = new AddMedicineRemindBean();
        bean.setId(id);
        bean.setDeleid(delIds);
        List<MultipartBody.Part> list = new ArrayList<>();
        String imgKey;
        if (medicineViewList.size() == 0) {
            AppUtil.showToast(this, "请选择药品");
            hideProgress();
            return;
        }
        for (int i = 0; i < medicineViewList.size(); i++) {
            AddMedicineRemindBean.ListBean bean1 = new AddMedicineRemindBean.ListBean();
            EditText etName = medicineViewList.get(i).getEtName();
            String medicineName = etName.getText().toString();
            if (TextUtils.isEmpty(medicineName)) {
                AppUtil.showToast(this, etName.getHint());
                etName.requestFocus();
                etName.requestFocusFromTouch();
                hideProgress();
                return;
            }
            bean1.setId(medicineViewList.get(i).getId());
            bean1.setDrugname(medicineName);
            bean1.setNumber(medicineViewList.get(i).getEtNum().getText().toString());
            File file = medicineViewList.get(i).getIconFile();
            if (file != null) {
                imgKey = MathUtil.getRandom(6, MathUtil.LETTER_CHAR);
                bean1.setImg(imgKey);
                MultipartBody.Part fileBody = HttpRequest.getPartFileBody(file, imgKey);
                list.add(fileBody);
            }
            bean.getList().add(bean1);
        }
        String time = "";
        for (int i = 0; i < timesList.size(); i++) {
            if (!"- - : - -".equals(timesList.get(i).getName())) {
                if (TextUtils.isEmpty(time)) {
                    time += timesList.get(i).getName();
                } else {
                    time += "," + timesList.get(i).getName();
                }
            }
        }
        if (TextUtils.isEmpty(time)) {
            AppUtil.showToast(this, "请选择提醒时间");
            hideProgress();
            return;
        }
        bean.setMedicinetime(time);
        if (!TextUtils.isEmpty(voicePath)) {
            File file = new File(voicePath);
            if (file != null && file.exists()) {
                bean.setRingtonestate("1");
                String voiceKey = MathUtil.getRandom(6, MathUtil.LETTER_CHAR);
                bean.setRingtone(voiceKey);
                MultipartBody.Part voiceBody = HttpRequest.getPartFileBody(file, voiceKey);
                list.add(voiceBody);
            }
        }
        if (isDelOriginalVoice && TextUtils.isEmpty(bean.getRingtone())) {
            bean.setRingtonestate("2");
        }
        bean.setType(type + "");
        bean.setTypevalue(value);
        bean.setUsername(username);
        bean.setDevice_id(device_id);
        bean.setTitle("吃药提醒");
        AppUtil.showLog(JSON.toJSONString(bean));

        Call<BaseBean> call;
        if (editBean == null) {
            call = HttpRequest.getService().addMedicineRemind(HttpRequest.getPartBody(JSON.toJSONString(bean)), list);
        } else {
            call = HttpRequest.getService().updateMedicineRemind(HttpRequest.getPartBody(JSON.toJSONString(bean)), list);
        }
        call.enqueue(new Callback<BaseBean>() {
            @Override
            public void onResponse(Call<BaseBean> call, Response<BaseBean> response) {
                hideProgress();
                BaseBean baseBean = response.body();
                if (baseBean != null && !TextUtils.isEmpty(baseBean.getMsg())) {
                    AppUtil.showToast(EditRemindActivity.this, baseBean.getMsg());
                } else {
                    if (editBean == null) {
                        AppUtil.showToast(EditRemindActivity.this, "添加成功");
                    } else {
                        AppUtil.showToast(EditRemindActivity.this, "修改成功");
                    }
                }
                if (baseBean != null && baseBean.getCode() == 200) {
                    EventBusManager.post(new EventBusBean.Builder().id(3).build());
                    setResult(RESULT_OK);
                    finish();
                }
            }

            @Override
            public void onFailure(Call<BaseBean> call, Throwable t) {
                hideProgress();
                AppUtil.showToast(EditRemindActivity.this, "网络错误，请稍后再试！");
            }
        });
    }

    private void addMedicineView(MedicineRemindDetailBean.DataBean.ResultdetailsBean medicineBean) {
        final View view = View.inflate(this, R.layout.item_medicine, null);
        final EditText et_name = view.findViewById(R.id.et_name);
        final EditText et_num = view.findViewById(R.id.et_num);
        ImageView iv_minus = view.findViewById(R.id.iv_minus);
        ImageView iv_plus = view.findViewById(R.id.iv_plus);
        ImageView iv_take_photo = view.findViewById(R.id.iv_take_photo);
        ImageView iv_delete = view.findViewById(R.id.iv_delete);

        final MedicineViewBean bean = new MedicineViewBean();
        bean.setEtName(et_name);
        bean.setEtNum(et_num);
        bean.setIvIcon(iv_take_photo);

        iv_delete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (TextUtils.isEmpty(delIds)) {
                    delIds += bean.getId();
                } else {
                    delIds += "," + bean.getId();
                }
                llMedicine.removeView(view);
                medicineViewList.remove(bean);
                for (MedicineViewBean medicineViewBean : medicineViewList) {
                    AppUtil.showLog(medicineViewBean.getEtNum().getText());
                }
            }
        });
        iv_minus.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                et_num.setText((MathUtil.parseInt(et_num.getText().toString().trim()) - 1) + "");
            }
        });
        iv_plus.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                et_num.setText((MathUtil.parseInt(et_num.getText().toString().trim()) + 1) + "");
            }
        });
        final int requestCode = medicineViewList.size();
        iv_take_photo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getPermission(requestCode, "该功能需要存储权限和相机权限", Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA);
            }
        });
        et_num.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                AppUtil.showLog(s);
                if (TextUtils.isEmpty(s) || (s + "").startsWith("0")) {
                    et_num.setText("1");
                    et_num.setSelection(et_num.getText().length());
                }
            }
        });
        if (medicineBean != null) {
            bean.setId(medicineBean.getId());
            bean.setIconUrl(HttpRequest.BASE_URL + medicineBean.getUrl());
            et_name.setText(medicineBean.getDrugname());
            et_num.setText(medicineBean.getNumber() + "");
            Glide.with(this).load(bean.getIconUrl()).apply(new RequestOptions().placeholder(R.mipmap.logo).error(R.mipmap.logo).override(DisplayUtil.dip2px(this, 60))).into(iv_take_photo);
        }
        medicineViewList.add(bean);
        llMedicine.addView(view);
    }

    private void delMedicineRemind() {
        if (TextUtils.isEmpty(id)) {
            AppUtil.showToast(this, "数据有误");
            return;
        }
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("id", id);
        RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), jsonObject.toJSONString());
        Call<BaseBean> call = HttpRequest.getService().delMedicineRemind(body);
        call.enqueue(new Callback<BaseBean>() {
            @Override
            public void onResponse(Call<BaseBean> call, Response<BaseBean> response) {
                BaseBean bean = response.body();
                if (bean != null) {
                    if (bean.getCode() == 200) {
                        if (!TextUtils.isEmpty(bean.getMsg())) {
                            AppUtil.showToast(EditRemindActivity.this, bean.getMsg());
                        } else {
                            AppUtil.showToast(EditRemindActivity.this, "删除成功");
                        }
                        EventBusManager.post(new EventBusBean.Builder().id(3).build());
                        setResult(RESULT_OK);
                        finish();
                        return;
                    }
                }
                if (bean != null && !TextUtils.isEmpty(bean.getMsg())) {
                    AppUtil.showToast(EditRemindActivity.this, bean.getMsg());
                } else {
                    AppUtil.showToast(EditRemindActivity.this, "网络错误，请稍后再试！");
                }
            }

            @Override
            public void onFailure(Call<BaseBean> call, Throwable t) {
                AppUtil.showToast(EditRemindActivity.this, "网络错误，请稍后再试！");
            }
        });
    }

    private void getPermission(int requestCode, String msg, String... permissions) {
        if (rxPermissions == null) {
            rxPermissions = new RxPermissions(this);
        }
        rxPermissions.requestEachCombined(permissions)
                .subscribe(permission -> {
                    if (permission.granted) {
                        if (requestCode != 10000) {
                            getPicture(1, requestCode);
                        }
                    } else if (permission.shouldShowRequestPermissionRationale) {
                        showPermissionDialog(msg, (dialog, which) -> {
                            if (requestCode != 10000) {
                                getPermission(requestCode, "该功能需要存储权限和相机权限", Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA);
                            } else {
                                getPermission(requestCode, "该功能需要录音权限", Manifest.permission.RECORD_AUDIO);
                            }
                        });
                    } else {
                        showPermissionDialog(msg);
                    }
                });
    }

    private void getPicture(int maxSelectable, int requestCode) {
        Matisse.from(this)
                .choose(MimeType.ofImage())
                .countable(true)
                .capture(true)
                .maxSelectable(maxSelectable)
                .captureStrategy(new CaptureStrategy(true, Constant.authority))
                .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT)
                .thumbnailScale(0.85f)
                .imageEngine(new GlideImageLoader.Glide4Engine())
                .forResult(requestCode);
    }

    private void compressImg(int requestCode, String faceIdPath) {
        File file = new File(faceIdPath);
        AppUtil.showLog(file.exists() + "：路径：" + file);
        CompressTools tool = new CompressTools.Builder(this).setDestinationDirectoryPath(FileUtil.getBaseImagePath(this)).build();
        tool.compressToFileJni(file, new CompressTools.OnCompressListener() {
            @Override
            public void onStart() {

            }

            @Override
            public void onSuccess(File file) {
                AppUtil.showLog(file.exists() + "压缩成功：" + file);
                medicineViewList.get(requestCode).setIconFile(file);
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == 10000) {
                handleResult(data);
            } else {
                mSelected = Matisse.obtainPathResult(data);
                AppUtil.showLog("mSelected: " + mSelected + "\n");
                if (mSelected != null && mSelected.size() > 0) {
                    String faceIdPath = mSelected.get(0);
                    compressImg(requestCode, faceIdPath);
                    Glide.with(this).load(faceIdPath).apply(new RequestOptions().placeholder(R.mipmap.logo).error(R.mipmap.logo).override(DisplayUtil.dip2px(this, 60))).into(medicineViewList.get(requestCode).getIvIcon());
                }
            }
        }
    }

    private void handleResult(Intent data) {
        repeatDateBean = (BaseRepeatDateBean) data.getSerializableExtra("data");
        type = repeatDateBean.getType();
        if (type == 0) {
            value = "1";
            civAddRepeat.setLeftText(repeatDateBean.getTitle());
        } else if (type == 1) {
            value = "";
            String name = "";
            List<BaseRepeatDateBean.DataBean> dataList = repeatDateBean.getData();
            int size = dataList.size();
            int selectCount = 0;
            for (int i = 0; i < size; i++) {
                BaseRepeatDateBean.DataBean bean = dataList.get(i);
                if (bean.isCheck()) {
                    selectCount++;
                    AppUtil.showLog(bean.getName() + "：" + bean.getId());
                    if ("".equals(value)) {
                        value += bean.getId();
                        name += "每" + bean.getName();
                    } else {
                        value += "," + bean.getId();
                        name += "、" + bean.getName();
                    }
                }
            }
            if (selectCount == 7) {
                type = 0;
                value = "1";
                name = "每天";
            }
            civAddRepeat.setLeftText(name);
        } else if (type == 2) {
            value = repeatDateBean.getData().get(0).getName();
            civAddRepeat.setLeftText("每隔" + value + "天");
        }
        AppUtil.showLog("类型：" + type);
        AppUtil.showLog("值：" + value);
    }

    private void getTime(final int position) {
//            Calendar selectedDate = Calendar.getInstance();
        Calendar startDate = Calendar.getInstance();
        //startDate.set(2013,1,1);
        Calendar endDate = Calendar.getInstance();
        //endDate.set(2020,1,1);
        //正确设置方式 原因：注意事项有说明
//                startDate.set(startDate.get(Calendar.YEAR), startDate.get(Calendar.MONTH), startDate.get(Calendar.DATE), startDate.get(Calendar.HOUR_OF_DAY), startDate.get(Calendar.MINUTE), startDate.get(Calendar.SECOND));
        endDate.set(2030, 11, 31);
        new TimePickerBuilder(EditRemindActivity.this, new OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {//选中事件回调
                timesList.set(position, new TimesBean(DateUtil.formDateToStr(date, DateUtil.hourToMinPattern), date.getTime()));
                adapter.strSort(timesList);
                adapter.notifyDataSetChanged();
//                tv_time.setText(new SimpleDateFormat("HH:mm").format(date));
                AppUtil.showLog(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date));
//                for (TextView textView : timeList) {
//                    AppUtil.showLog(textView.getText());
//                }
            }
        }).setType(new boolean[]{false, false, false, true, true, false})// 默认全部显示
                .setCancelText("取消")//取消按钮文字
                .setSubmitText("确认")//确认按钮文字
                .setContentTextSize(25)//滚轮文字大小
//                        .setTitleSize(20)//标题文字大小
                .setTitleText("请选择提醒时间")//标题文字
//                    .setOutSideCancelable(false)//点击屏幕，点在控件外部范围时，是否取消显示
//                    .isCyclic(true)//是否循环滚动
                .setTitleColor(Color.WHITE)//标题文字颜色
                .setSubmitColor(Color.WHITE)//确定按钮文字颜色
                .setCancelColor(Color.WHITE)//取消按钮文字颜色
                .setTitleBgColor(getResources().getColor(R.color.main_blue))//标题背景颜色 Night mode
                .setBgColor(Color.WHITE)//滚轮背景颜色 Night mode
                .setTextColorCenter(getResources().getColor(R.color.black_2A2A2A))
//                    .setDate(selectedDate)// 如果不设置的话，默认是系统时间*/
                .setRangDate(startDate, endDate)//起始终止年月日设定
                .setLabel(null, null, null, "时", "分", null)//默认设置为年月日时分秒
                .isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
                .isDialog(false)//是否显示为对话框样式
                .build().setOnDismissListener(new OnDismissListener() {
            @Override
            public void onDismiss(Object o) {
                EventBusManager.post(new EventBusBean.Builder().id(8).build());
            }
        }).show();
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            // 获得当前得到焦点的View，一般情况下就是EditText（特殊情况就是轨迹求或者实体案件会移动焦点）
            View v = getCurrentFocus();
            if (AppUtil.isShouldHideInput(v, ev)) {
                AppUtil.hideSoftInput(this, v.getWindowToken());
            }
        }
        return super.dispatchTouchEvent(ev);
    }

    @Override
    public void onEventBus(EventBusBean busBean) {
        super.onEventBus(busBean);
        if (busBean.getId() == 5) {
            getPermission(10000, "该功能需要录音权限", Manifest.permission.RECORD_AUDIO);
        }
    }
}
